import { request } from '@/utils/request';
import { LoginData, RegisterData, TokenResponse, UserProfile } from '@/types/user';

export async function login(data: LoginData): Promise<TokenResponse> {
  return request('/api/v1/auth/login', {
    method: 'POST',
    data,
  });
}

export async function register(data: RegisterData): Promise<UserProfile> {
  return request('/api/v1/auth/register', {
    method: 'POST',
    data,
  });
}

export async function getCurrentUser(): Promise<UserProfile> {
  return request('/api/v1/users/me');
}

export async function fetchGraphData(params?: string) {
  try {
    const response = await fetch(`/api/v1/graph/graph-data${params || ''}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    
    if (!response.ok) {
      throw new Error('获取图谱数据失败');
    }
    
    return response.json();
  } catch (error) {
    console.error('请求图谱数据出错:', error);
    throw error;
  }
}

export async function resetPassword(data: { 
  email: string; 
  old_password: string; 
  new_password: string; 
}): Promise<{ message: string }> {
  return request('/api/v1/auth/reset-password', {
    method: 'POST',
    data,
  });
}

interface CommentResponse {
  id: string;
  content: string;
  user: {
    name: string;
    avatar: string;
  };
  likes: number;
  replies: CommentResponse[];
  createdAt: string;
}

// 获取评论时添加用户ID参数
export const fetchComments = async () => {
  const currentUser = JSON.parse(localStorage.getItem('user') || '{}');
  const response = await request('/api/v1/comments', {
    method: 'GET',
    params: {
      user_id: currentUser.id
    }
  });
  return response;
};

// 提交评论时添加用户信息
export const submitComment = async (data: {
  content: string;
  user_id: string;
  user_email: string;
  user_name: string;
}): Promise<CommentResponse> => {
  try {
    const response = await request('/api/v1/comments', {
      method: 'POST',
      data
    });
    return response;
  } catch (error) {
    console.error('提交评论失败:', error);
    throw error;
  }
};

export async function submitReply(commentId: string, content: string) {
  const currentUser = JSON.parse(localStorage.getItem('user') || '{}');
  return request(`/api/v1/comments/${commentId}/reply`, {
    method: 'POST',
    data: {
      content,
      user_id: currentUser.id,
      user_email: currentUser.email,
      user_name: currentUser.name || currentUser.email.split('@')[0]
    }
  });
}

export async function likeComment(commentId: string) {
  return request(`/api/v1/comments/${commentId}/like`, {
    method: 'POST'
  });
}

export async function searchContent(keyword: string, page: number = 1, pageSize: number = 10) {
  const params = new URLSearchParams({
    keyword,
    page: String(page),
    page_size: String(pageSize)
  });
  
  return request(`/api/v1/search?${params}`);
}